<template>
  <div>
    <!-- 面包屑 -->
    <breadcrumb
      :breadcrumbArr="jsList.breadcrumbArr"
      :breadcrumbLastItem="breadcrumbLastItem"
      :state="state"
      @handleBack="handleBack"
    />
    <div v-if="isTrue" class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          class="el-tabs__customize"
          @tab-click="handleTabsClick"
        >
          <el-tab-pane label="基本信息" name="first">
            <baseInfo ref="baseInfo" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="财务信息" name="second">
            <financeInfo ref="financeInfo" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="采购清单" name="third">
            <purchaseList ref="purchaseList" :detail="detailInfo" />
          </el-tab-pane>

          <el-tab-pane label="使用范围" name="fourth">
            <useRange ref="useRange" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="付款方式" name="fifth">
            <paymentMode ref="paymentMode" :detail="detailInfo" isChange />
          </el-tab-pane>

          <el-tab-pane label="合同附件" name="sixth">
            <contractAppendix
              ref="contractAppendix"
              :uploadBusinessType="2"
              :state="state"
              v-model="uploadList"
            />
          </el-tab-pane>

          <el-tab-pane label="变更历史" name="seventh">
            <oneLineTable
              ref="histryChanges"
              :highlightNodeArr="['contractCode']"
              :tableTheadOptions="baseJsObj.histryChangeTableThead"
              :oneLineTableData="detailInfo.oldSmpPcConcList"
              @gotoDetail="gotoDetail"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(0)"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle(1)"
            >保存并提交</el-button
          >
        </li>
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import jsList from "../js";
import baseJsObj from "@/app/contractManagement/materialContract/contractDraft/js"; // 变更历史用js
import { cloneDeep } from "lodash";
import baseInfo from "../components/baseInfo";
// import contractComponent from "@/app/contractManagement/components";
import financeInfo from "../components/financeInfo.vue";
import useRange from "../components/useRange.vue";
import paymentMode from "../components/paymentMode.vue";
import contractAppendix from "../components/changeUploadInfo.vue";
import purchaseList from "../components/purchaseList";
import publicComponent from "@/basa/components/public";
import Mixin from "../mixins";
import {
  saveSmpContractCreation,
  editSmpContractCreation,
  getSmpPcConcChangeById
} from "../api";
import { mapActions, mapGetters } from "vuex";
import { proxyDateFormat } from "@/basa/utils";
export default {
  mixins: [Mixin],
  components: {
    financeInfo,
    useRange,
    paymentMode,
    contractAppendix,
    baseInfo,
    // financeInfo:contractComponent.financeInfo,
    purchaseList,
    // useRange:contractComponent.useRange,
    // paymentMode:contractComponent.paymentMode,
    // contractAppendix:contractComponent.changeUploadInfo,
    breadcrumb: publicComponent.breadcrumb,
    oneLineTable: publicComponent.oneLineTable
  },
  data() {
    return {
      jsList,
      baseJsObj,
      breadcrumbLastItem: "合同变更",
      activeName: "first",
      isTrue: false,
      detailInfo: {},
      isFocus: "baseInfo",
      uploadList: [],
      tabsSelectArr: [],
      taxRateObj: {},
      afterVal: "",
      state: "create",
      watchChangeList: {},
      lastFileSn: 0
    };
  },
  created() {
    this.init();
  },
  activated() {
    this.init();
  },
  deactivated() {
    this.nextIsTrue();
  },
  methods: {
    init() {
      this.getSmpPcConcInfo();
    },

    handleTabsClick({ label, name }) {
      if (this.tabsSelectArr.includes(name)) return;
      this.tabsSelectArr.push(name);
      this.detailInfo.tState = this.tState++;
    },

    // 保存 提交
    async submitHandle(operType) {
      try {
        // 基础合同
        let smpPcConcBO = await this.$refs.baseInfo.handleSubmit();
        // 财务信息
        let pcFinanceBOS = await this.$refs.financeInfo.handleSubmit();
        // 采购清单
        let smpConcMatLessListBOList = await this.$refs.purchaseList.handleSubmit();
        // 使用范围
        let smpUsableRangeBOList = await this.$refs.useRange.handleSubmit();
        // 付款方式
        let payTypeListBOS = await this.$refs.paymentMode.handleSubmit();

        if (pcFinanceBOS.length) {
          pcFinanceBOS.forEach(item => {
            item.materialSource = smpPcConcBO.materialSource;
            item.materialSourceCode = smpPcConcBO.materialSourceCode;
            item.contractPerson = smpPcConcBO.contractPerson;
            item.contractPersonTel = smpPcConcBO.contractPersonTel;
          });
        }

        let thirdCategoriesOfName = "";
        if (smpConcMatLessListBOList && smpConcMatLessListBOList.length) {
          thirdCategoriesOfName =
            smpConcMatLessListBOList[0].thirdCategoriesOfName;
          if (this.taxRateObj.dicValue !== "免税") {
            const newVal = this.taxRateObj.dicValue
              ? this.taxRateObj.dicValue.match(/\d+(.\d+)?/g)[0]
              : 0;
            this.afterVal = Number(newVal) / 100;
          } else {
            this.afterVal = this.taxRateObj.dicKey;
          }

          if (!this.getMultiRateCode) {
            smpConcMatLessListBOList = smpConcMatLessListBOList.map(n => ({
              ...n,
              taxRateCode: this.taxRateObj.dicKey,
              taxRatePercent: this.taxRateObj.dicValue,
              taxRate: this.afterVal
            }));
            // 采购清单改变状态
            let oldList = this.watchChangeList.smpConcMatLessList;
            smpConcMatLessListBOList.forEach((m, index) => {
              if (oldList[index]) {
                if (
                  oldList[index].taxRatePercent != m.taxRatePercent ||
                  oldList[index].address != m.address ||
                  oldList[index].currentUnitPriceIncludeTax !=
                    m.currentUnitPriceIncludeTax ||
                  oldList[index].currentNum != m.currentNum ||
                  oldList[index].matDescribe != m.matDescribe
                ) {
                  console.log(
                    "不同走1",
                    oldList[index].taxRatePercent != m.taxRatePercent,
                    oldList[index].address != m.address,
                    oldList[index].currentUnitPriceIncludeTax !=
                      m.currentUnitPriceIncludeTax,
                    oldList[index].currentNum != m.currentNum,
                    oldList[index].matDescribe != m.matDescribe
                  );
                  this.$set(m, "isChangeFlag", 1);
                } else {
                  console.log("相同同走0");
                  this.$set(m, "isChangeFlag", 0);
                }
              } else {
                console.log(`这是新增行${index}`);
              }
            });
          }
        }
        // 使用范围变更状态
        let oldUseAbleList = this.watchChangeList.smpUsableRange;
        smpUsableRangeBOList.forEach((m, index) => {
          // applyOrgName
          if (oldUseAbleList[index]) {
            if (oldUseAbleList[index].applyOrgName != m.applyOrgName) {
              this.$set(m, "isChangeFlag", 1);
            } else {
              this.$set(m, "isChangeFlag", 0);
            }
          } else {
            console.log(`这是新增行${index}`);
          }
        });

        // 付款方式变成状态
        let oldPayModeList = this.watchChangeList.payTypeListBOS;
        payTypeListBOS.forEach((m, index, arr) => {
          console.log(`付款第${index}个`);
          // 先比较发票或结算
          // 判断old是否有当前可对比内容，否则为新增
          if (oldPayModeList[index]) {
            if (
              m.smpPayTypeBO.payType !==
              oldPayModeList[index].smpPayTypeBO.payType
            ) {
              arr[index].smpPayTypeBO.isChangeFlag = 1;
            } else {
              arr[index].smpPayTypeBO.isChangeFlag = 0;
            }
            // 再比较列表
            payTypeListBOS[index].smpPayTypeItemBOS.forEach((n, i, Arr) => {
              if (oldPayModeList[index].smpPayTypeItemBOS[i]) {
                n.isRetentionMoney =
                  n.isRetentionMoney == null ? [] : n.isRetentionMoney;
                oldPayModeList[index].smpPayTypeItemBOS[i].isRetentionMoney =
                  oldPayModeList[index].smpPayTypeItemBOS[i].isRetentionMoney ==
                  null
                    ? []
                    : oldPayModeList[index].smpPayTypeItemBOS[i]
                        .isRetentionMoney;

                if (n.fixTimeCode === 0) {
                  if (
                    n.fixTimeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].fixTimeCode ||
                    n.fixTimeLength !==
                      oldPayModeList[index].smpPayTypeItemBOS[i]
                        .fixTimeLength ||
                    n.fixTimeSonCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i]
                        .fixTimeSonCode ||
                    n.payTypeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payTypeCode ||
                    n.payRate !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payRate ||
                    n.isRetentionMoney.toString() !==
                      oldPayModeList[index].smpPayTypeItemBOS[
                        i
                      ].isRetentionMoney.toString()
                  ) {
                    console.log("f0走1");
                    Arr[i].isChangeFlag = 1;
                  } else {
                    Arr[i].isChangeFlag = 0;
                  }
                } else if (n.fixTimeCode === 3) {
                  if (
                    n.fixTimeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].fixTimeCode ||
                    n.datePicker !==
                      oldPayModeList[index].smpPayTypeItemBOS[i]
                        .fixTimeLength ||
                    n.payTypeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payTypeCode ||
                    n.payRate !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payRate ||
                    n.isRetentionMoney.toString() !==
                      oldPayModeList[index].smpPayTypeItemBOS[
                        i
                      ].isRetentionMoney.toString()
                  ) {
                    console.log("f3走1");
                    Arr[i].isChangeFlag = 1;
                  } else {
                    Arr[i].isChangeFlag = 0;
                  }
                } else if (n.fixTimeCode === 5) {
                  if (
                    n.fixTimeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].fixTimeCode ||
                    n.payTypeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payTypeCode ||
                    n.payRate !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payRate ||
                    n.isRetentionMoney.toString() !==
                      oldPayModeList[index].smpPayTypeItemBOS[
                        i
                      ].isRetentionMoney.toString()
                  ) {
                    console.log("f5走1");
                    Arr[i].isChangeFlag = 1;
                  } else {
                    Arr[i].isChangeFlag = 0;
                  }
                } else {
                  // let retentionState = n.isRetentionMoney.length
                  //   ? n.isRetentionMoney[0]
                  //   : [];
                  if (
                    n.fixTimeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].fixTimeCode ||
                    n.fixTimeLength !==
                      oldPayModeList[index].smpPayTypeItemBOS[i]
                        .fixTimeLength ||
                    n.payTypeCode !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payTypeCode ||
                    n.payRate !==
                      oldPayModeList[index].smpPayTypeItemBOS[i].payRate ||
                    n.isRetentionMoney.toString() !==
                      oldPayModeList[index].smpPayTypeItemBOS[
                        i
                      ].isRetentionMoney.toString()
                  ) {
                    console.log("fe走1");
                    Arr[i].isChangeFlag = 1;
                  } else {
                    Arr[i].isChangeFlag = 0;
                  }
                }
              } else {
                console.log(`${index}块的${i}是新增行`);
              }
            });
          } else {
            console.log(`${index}是新增块`);
          }
        });

        smpPcConcBO = {
          ...smpPcConcBO,
          thirdCategoriesOfName,
          id: null
        };

        // 附件上传
        const fileReqBOS = this.uploadList
          .filter(_ => _.businessSonType === "3" && _.addFlag)
          .map((n, i) => ({
            sn: this.lastFileSn + i + 1,
            createTime: n.createTime,
            fileDesc: n.fileDesc,
            fileInfoId: n.uploadId || n.fileInfoId
          }));

        if (smpPcConcBO.checkDate) delete smpPcConcBO.checkDate;

        if (payTypeListBOS.length) {
          payTypeListBOS = payTypeListBOS.map((n, i) => ({
            smpPayTypeBO: {
              ...n.smpPayTypeBO,
              sn: i,
              id: null
            },
            smpPayTypeItemBOS: n.smpPayTypeItemBOS.map((m, i) => ({
              ...m,
              sn: i,
              id: null
            }))
          }));
        }

        const data = {
          smpPcConcBO,
          pcFinanceBOS,
          smpConcMatLessListBOList,
          smpUsableRangeBOList,
          payTypeListBOS,
          fileReqBOS, // 合同附件
          operType
        };

        (this.state === "create"
          ? saveSmpContractCreation
          : editSmpContractCreation)(data).then(res => {
          const { code, message } = res.data;
          if (code === "0") {
            this.$message.success(message);
            this.handleBack();
          }
        });
      } catch (error) {
        this.activeName = error;
        if (["first", "second"].includes(error)) {
          this.$nextTick(() => {
            const errorFormEl = document.body.querySelector(".is-error");
            const errorText = errorFormEl.firstChild.innerText;
            const messageText = errorText.substring(
              0,
              errorText.lastIndexOf("：")
            );
            this.$showErrorMessage(`${messageText}未填写，请编辑后保存`);
            if (errorFormEl) {
              errorFormEl.scrollIntoView({
                behavior: "smooth", // 平滑过渡
                block: "start" // 上边框与视窗顶部平齐。默认值
              });
            }
          });
        }
      }
    },

    // 获取详情
    getSmpPcConcInfo() {
      const { id } = this.$route.params;
      const data = { concId: id, isShowWorkflow: 1 };
      getSmpPcConcChangeById(data)
        .then(res => {
          const {
            data: { data }
          } = res;

          this.$nextTick(() => {
            this.setTaxRateObj({
              dicKey: data.smpPcConc.taxRateCode,
              dicValue: data.smpPcConc.taxRatePercent
            });
            this.setCurrencyObj({
              code: data.smpPcConc.currencyCode,
              name: data.smpPcConc.currencyName
            });
            this.setOrgId(data.smpPcConc.reportInOrgId);
            this.setTaxRate(data.smpPcConc.taxRate / 100);
            this.setMultiRateCode(
              data.smpPcConc.multiRateCode === 0 ? true : false
            );
            this.setMultiRateStatus(false);
            this.setShowDoubleTable(!!data.smpPcConc.partyBId);
            this.setSupplierData({ supplierCode: data.smpPcConc.partyBId });
            this.setAgreementSelectStatus(!!data.smpPcConc.protocalCode);
            this.setIsOverseas(data.smpPcConc.isOverseas);
          });

          // 处理变更历史
          if (data.oldSmpPcConcList.length) {
            data.oldSmpPcConcList = data.oldSmpPcConcList.map(n => ({
              ...n,
              compileDateStr: n.compileDate
                ? proxyDateFormat(n.compileDate)
                : ""
            }));
          }

          // 处理采购清单
          if (data.smpConcMatLessList.length) {
            data.smpConcMatLessList = data.smpConcMatLessList.map(n => ({
              ...n,
              deliveryTime: n.deliveryTime
                ? proxyDateFormat(n.deliveryTime)
                : "",
              currentNum: n.currentNum !== null ? n.currentNum.toFixed(3) : "",
              currentUnitPriceExcludeTax:
                n.currentUnitPriceExcludeTax !== null
                  ? n.currentUnitPriceExcludeTax.toFixed(2)
                  : "",
              currentChangeAmtExcludeTax:
                n.currentChangeAmtExcludeTax !== null
                  ? n.currentChangeAmtExcludeTax.toFixed(2)
                  : "",
              currentUnitPriceIncludeTax:
                n.currentUnitPriceIncludeTax !== null
                  ? n.currentUnitPriceIncludeTax.toFixed(2)
                  : "",
              currentChangeAmtIncludeTax:
                n.currentChangeAmtIncludeTax !== null
                  ? n.currentChangeAmtIncludeTax.toFixed(2)
                  : "",
              rate: n.rate !== null ? n.rate.toFixed(2) : ""
            }));
            this.setEchoProtocalData(data.smpConcMatLessList);
          }

          this.detailInfo = Object.assign(data, {
            state: this.state
          });

          this.watchChangeList = cloneDeep(this.detailInfo);
          this.watchChangeList.smpConcMatLessList = this.watchChangeList.smpConcMatLessList.map(
            n => ({
              ...n,
              address:
                (n.deliveryAreaName || "") +
                (n.provinceName || "") +
                (n.cityName || "") +
                (n.countyName || "") +
                (n.deliveryPoints || "") // 交货地点
            })
          );

          // 过滤附件
          this.uploadList = data.concFiles;
          this.lastFileSn = data.concFiles.length
            ? data.concFiles.slice(-1)[0].sn
            : 0;

          this.isTrue = true;
        })
        .catch(e => {});
    },

    gotoDetail({ id }) {
      this.$router.push(
        `/contractManagement/materialRentContractChange/contractChangeDetail/${id}`
      );
    },

    diff(arr1, arr2) {
      return arr1.filter(_ => !new Set(arr2).has(_));
    },

    ...mapActions([
      "setTaxRate",
      "setTaxRateObj",
      "setOrgId",
      "setMultiRateCode",
      "setMultiRateStatus",
      "setShowDoubleTable",
      "setSupplierData",
      "setAgreementSelectStatus",
      "setEchoProtocalData",
      "setIsOverseas",
      "setCurrencyObj"
    ])
  },
  computed: {
    ...mapGetters(["getTaxRateObj", "getMultiRateCode"])
  },
  watch: {
    getTaxRateObj(newVal) {
      this.taxRateObj = newVal;
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tabs__customize {
  padding-bottom: 50px;
}
</style>
